/*
    This file is part of p4f
    Copyright (C) 2009  Sebastian Fernandez

    p4f is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as 
    published by the Free Software Foundation, either version 3 of the 
    License, or (at your option) any later version.

    p4f is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

#include <http.h>

#define MAX_RECV 2048

HTTPServer::HTTPServer()
{
	http_resources = NULL;
}

bool HTTPServer::serve(int port)
{
	if(listen(port) == false)
		return false;
	start();
	return true;
}

void HTTPServer::run(void *d)
{
	Socket *s;
	Parser *p;
	std::string res;
	char *data;
	char *tmp;
	int length=0;

	data = (char *)malloc(MAX_RECV);
	lentgth = MAX_RECV;

	while(1){
		s = accept();
		s->recv(data, length);
		p = new Parser(data, length);
		p.find_word("GET");
		p.set_separator(" \t");
		tmp = p.get_next();
		res = tmp;
		free(tmp);
		if(serve_res(res)){
			//Serve the resource
		}
		else if(serve_res_global()){
			//Serve global resource
		}
		else{
			serve_p4f_msg();
			//Show our "P4f" pretty msg :P
		}
	}
}

bool HTTPServer::serve_res(std::string nres)
{
	int i = 0;
	if(http_resources==NULL)
		return false;
	for(i = 0; http_resources[i]!=NULL; i++){
		if(nres == http_resources[i].name){
		//if(strcmp(http_resources[i].name.c_str(), nres)==0){
			http_send(http_resources[i].data, http_resources[i].length,
					http_resources[i].type);
		}
	}
	return false;
}

void HTTPServer::http_send(char *data, int length, std::string type)
{
	
}
